//
//  RHAddUserVC.m
//  RuiHeAppApp
//
//  Created by Yan Chen on 2023/11/7.
//

#import "RHAddUserVC.h"
#import "NSAttributedString+YYText.h"
#import "YYLabel.h"
#import "RHAuthCodeViewController.h"
#import "RHCustomTimer.h"
#import "LCMD5Tool.h"
#import "RHChioceRegionTypeVC.h"
#import "RHGolbalRegionModel.h"
#import "NetworkConfig.h"
#import "EnvironmentManage.h"

@interface RHAddUserVC ()
@property (nonatomic ,strong) UIView *contentView;

@property (nonatomic ,strong) QMUIButton *sendBtn;

@property (nonatomic ,strong) NSMutableArray *TFArr;

@property (nonatomic, strong) NSTimer *timer;

@property (nonatomic, assign) int second;

@property (nonatomic ,strong) NSArray *countryListArr;

@property (nonatomic, strong) RHGolbalRegionModel *regionModel;

@property (nonatomic, strong) NSArray *filterAreaArr;
@end

@implementation RHAddUserVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"创建用户".rh_localized;
    self.view.backgroundColor = [UIColor whiteColor];
    [self setupUI];
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
}

-(void)seccondReduce{
    self.second--;
    if(self.second ==0){
        [self.timer invalidate];
        self.title = nil;
        [self.sendBtn setTitle:@"获取验证码".rh_localized forState:UIControlStateNormal];
        [self.sendBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [self.sendBtn setBackgroundColor:CMainColorGreen];
        self.sendBtn.userInteractionEnabled = YES;
    }else{
        [self.sendBtn setTitle:[NSString stringWithFormat:@"%d",self.second] forState:UIControlStateNormal];
        [self.sendBtn setTitleColor:CMainColorGreen forState:UIControlStateNormal];
        [self.sendBtn setBackgroundColor:kCOLOR_HEX(@"E7E7E7")];
        self.sendBtn.userInteractionEnabled = NO;
        
    }
}
- (void)setupUI{
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(appBecomActive) name:UIApplicationDidBecomeActiveNotification object:nil];
    
    self.second = 60;
    [self.view setBackgroundColor:UIColor.whiteColor];
    _TFArr = [NSMutableArray array];
    UIView *bg = [[UIView alloc] init];
    [bg setBackgroundColor:[UIColor.blackColor colorWithAlphaComponent:0.5]];
    [self.view addSubview:bg];
    
    UIScrollView *scroll = [[UIScrollView alloc] init];
    [self.view addSubview:scroll];
    scroll.backgroundColor = [UIColor clearColor];
    
    kWeakSelf;
    [scroll mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(weakSelf.view);
    }];
    
    _contentView = [[UIView alloc] init];
    _contentView.backgroundColor = [UIColor clearColor];
    [scroll addSubview:_contentView];
    
    [self.contentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(scroll);
        make.width.mas_equalTo(scroll);
        make.height.greaterThanOrEqualTo(@0.f);//此处保证容器View高度的动态变化 大于等于0.f的高度
    }];
    
    
    
    UIView *bg_view = [[UIView alloc] init];
    [bg_view setBackgroundColor:UIColor.clearColor];
    [_contentView addSubview:bg_view];

    BOOL isBrand = [PrivateMange share].currentUser.hierarchyCode == UserRoleTypeBrandMerchants;
    
    NSArray *titles = @[@"国家/地区".rh_localized,@"邮箱".rh_localized,@"账号".rh_localized,@"验证码".rh_localized,@"新密码".rh_localized,@"确认密码".rh_localized];
    NSArray *placeholders = @[@"请选择一个国家/地区".rh_localized,@"请输入邮箱".rh_localized,@"请输入账号".rh_localized,@"请输入验证码".rh_localized,@"请输入新密码".rh_localized,@"请确认密码".rh_localized];
   
    NSMutableArray *array = [NSMutableArray array];
    [titles enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        UIView *view = [[UIView alloc] init];
       
        [view setBackgroundColor:UIColor.clearColor];
        [bg_view addSubview:view];
        [array addObject:view];
        
        
        if(!isBrand && idx == 0){//如果是品牌商创建国代用户,地区选择框要显示,其他角色不显示,因为已经存在区域
            view.hidden = YES;
        }
        
        QMUILabel *lab = [[QMUILabel alloc] init];
        [lab setTextAlignment:NSTextAlignmentLeft];
        [lab setFont:[UIFont systemFontOfSize:13]];
        [lab setTextColor:kCOLOR_HEX(@"333333")];
        [lab setText:obj];
        [view addSubview:lab];

        [lab mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_offset(5);
            make.top.mas_offset(5);
            make.right.mas_offset(-5);
            make.height.mas_equalTo(15);
        }];
        
        //边框
        UIView *textField_bg = [[UIView alloc] init];
        [textField_bg.layer setBorderColor:kCOLOR_HEX(@"DCDCDC").CGColor];
        [textField_bg.layer setBorderWidth:1.0];
        [textField_bg.layer setCornerRadius:5.0];
        [view addSubview:textField_bg];
        
        
        
        if(idx == 3){
            _sendBtn = [QMUIButton buttonWithType:UIButtonTypeCustom];
            _sendBtn.backgroundColor = CMainColorGreen;
            _sendBtn.layer.cornerRadius = 8;
            [_sendBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
            [_sendBtn setTitle:@"获取验证码".rh_localized forState:UIControlStateNormal];
            _sendBtn.titleLabel.font = [UIFont systemFontOfSize:13];
            _sendBtn.titleLabel.numberOfLines = 0;
            _sendBtn.titleLabel.textAlignment = NSTextAlignmentCenter;
            [view addSubview:_sendBtn];
            CGFloat width = [_sendBtn.titleLabel.text getStringWidthFont:_sendBtn.titleLabel.font limitHeight:20];
            [_sendBtn mas_makeConstraints:^(MASConstraintMaker *make) {
                make.top.equalTo(lab.mas_bottom).offset(5);
                make.right.mas_offset(-5);
                make.bottom.mas_offset(0);
                make.width.offset(width+15);
            }];
            
            
            [textField_bg mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.mas_offset(5);
                make.right.equalTo(weakSelf.sendBtn.mas_left).offset(-20);
                make.bottom.mas_offset(0);
                make.top.equalTo(lab.mas_bottom).offset(5);
            }];
            
            
            
#pragma mark -----             //获取验证码
             [[_sendBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
                 [weakSelf.view endEditing:YES];
                 //邮箱校验
                 NSString *email =  [(QMUITextField*)weakSelf.TFArr[1] text];
                  if(![NSString isValidateEmail:email]){
                      [QMUITips showError:@"邮箱格式错误".rh_localized];
                      return;
                  }
                  
                 NSDictionary *para = @{@"sendEmail":[(QMUITextField*)weakSelf.TFArr[1] text],
                                        @"action":@"创建下级用户,获取验证码"};
                 [QMUITips showLoadingInView:weakSelf.view];
                 [BaseModel startWithCompletionAPIKey:H_sendCodeNoToken header:@{@"brandId":[NetworkConfig sharedConfig].brandID} argument:para requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
                     if (resultModel.code == 200) {
                         weakSelf.sendBtn.userInteractionEnabled = NO;
                         
                         weakSelf.second = 60;
                         [weakSelf seccondReduce];
                         weakSelf.timer = [RHCustomTimer scheduledTimerWithTimeInterval:1 target:weakSelf selector:@selector(seccondReduce) userInfo:nil repeats:YES];
                         [[NSRunLoop currentRunLoop]addTimer:weakSelf.timer forMode:NSRunLoopCommonModes];
                     }
                     

                 } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {

                 }];
             }];
        }else{
            [textField_bg mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.mas_offset(5);
                make.right.mas_offset(-5);
                make.bottom.mas_offset(0);
                make.top.equalTo(lab.mas_bottom).offset(5);
            }];
        }
        
        
        QMUITextField *textField = [[QMUITextField alloc] init];
        textField.font = kSYSTEMFONT(15);
        [textField setPlaceholder:placeholders[idx]];
        [textField_bg addSubview:textField];
        textField.tag = idx;
        [_TFArr addObject:textField];
        
        //选择国家按钮
        if(idx == 0){
            textField.userInteractionEnabled = NO;
            QMUIButton *countryBtn = [QMUIButton buttonWithType:UIButtonTypeCustom];
            countryBtn.imagePosition = QMUIButtonImagePositionRight;
            [countryBtn setTitle:@" " forState:UIControlStateNormal];
            countryBtn.spacingBetweenImageAndTitle = kUI_WINDOW_W - 30-40;
            [textField_bg addSubview:countryBtn];
            [countryBtn setImage:[UIImage imageNamed:@"nav_arrow_down"] forState:UIControlStateNormal];
            [countryBtn addTarget:self action:@selector(getCountryByServer) forControlEvents:UIControlEventTouchUpInside];
            [countryBtn mas_makeConstraints:^(MASConstraintMaker *make) {
                make.edges.insets(UIEdgeInsetsZero);
            }];
        }
        
        if(idx == 1){//邮箱
            textField.maximumTextLength = 64;
            textField.keyboardType = UIKeyboardTypeEmailAddress;
        }
        if(idx == 2){//用户名
            textField.maximumTextLength = 20;
            textField.keyboardType = UIKeyboardTypeASCIICapable;
        }
        if(idx == 3){//验证码
            textField.maximumTextLength = 6;
            textField.keyboardType = UIKeyboardTypePhonePad;
        }
        if(idx == 4||idx == 5){//密码
            textField.maximumTextLength = 16;
            textField.keyboardType = UIKeyboardTypeASCIICapable;
            textField.secureTextEntry = YES;
            //隐藏/显示密码
            QMUIButton *showPwdBtn = [[QMUIButton alloc]init];
            [showPwdBtn setImage:[UIImage imageNamed:@"kwt_show_pwd"] forState:UIControlStateNormal];
            [showPwdBtn setImage:[UIImage imageNamed:@"kwt_show_pwd_s"] forState:UIControlStateSelected];
            [textField_bg addSubview:showPwdBtn];
            [showPwdBtn mas_makeConstraints:^(MASConstraintMaker *make) {
                make.width.height.offset(35);
                make.right.equalTo(textField).offset(-5);
                make.centerY.equalTo(textField);
            }];
            
            [[showPwdBtn rac_signalForControlEvents:UIControlEventTouchUpInside]subscribeNext:^(__kindof UIButton * _Nullable x) {
                x.selected = !x.selected;
                textField.secureTextEntry = !x.selected;
            }];
        }
        
        
        [textField mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.insets(UIEdgeInsetsMake(2, 5, 2, 5));
        }];
        
        
    }];
    
    [array mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(10);
        make.right.mas_offset(-10);
    }];
    
    [array mas_distributeViewsAlongAxis:MASAxisTypeVertical withFixedItemLength:70 leadSpacing:isBrand?10:-70 tailSpacing:40];
    CGFloat height = (titles.count-1)*80 +40;
    if (isBrand) {
        height = titles.count * 80 +40;
    }
    [bg_view mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_offset(0);
        make.top.mas_offset(0);
        make.height.mas_equalTo(height);
    }];
    
    UIView *foot_view = [[UIView alloc] init];
    [foot_view setBackgroundColor:UIColor.clearColor];
    [_contentView addSubview:foot_view];
    
    
    QMUIButton *addButton = [QMUIButton buttonWithType:UIButtonTypeCustom];
    [addButton setTitle:@"创建".rh_localized forState:UIControlStateNormal];
    [addButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [addButton.titleLabel setFont:[UIFont systemFontOfSize:16]];
    [addButton setBackgroundColor:CMainColorGreen];
    [addButton.layer setCornerRadius:5];
    [addButton setContentHorizontalAlignment:UIControlContentHorizontalAlignmentCenter];
    [foot_view addSubview:addButton];
    

    [addButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(15);
        make.right.mas_offset(-15);
        make.height.mas_equalTo(50);
        make.top.mas_offset(50);
    }];
    
    
    [foot_view mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(0);
        make.right.mas_offset(0);
        make.top.equalTo(bg_view.mas_bottom);
        make.bottom.mas_offset(-30);
        make.height.mas_equalTo(200);
    }];

   
    

    [[addButton rac_signalForControlEvents:UIControlEventTouchUpInside]subscribeNext:^(__kindof UIControl * _Nullable x) {
        [weakSelf createSubUser];
    }];
}

#pragma mark -----    //添加子用户
-(void)createSubUser
{
    //国家地区
    BOOL isBrand = [PrivateMange share].currentUser.hierarchyCode == UserRoleTypeBrandMerchants;
    
    NSString *country =  [(QMUITextField*)self.TFArr[0] text];
     if(country.length == 0 && isBrand){
         [QMUITips showError:@"请选择一个国家/地区".rh_localized];
         return;
     }
    
    //邮箱校验
    NSString *email =  [(QMUITextField*)self.TFArr[1] text];
     if(![NSString isValidateEmail:email]){
         [QMUITips showError:@"邮箱格式错误".rh_localized];
         return;
     }
    
    //用户名校验
    NSString *userName =  [(QMUITextField*)self.TFArr[2] text];
     if(![NSString validateUserName:userName]){
         [QMUITips showError:@"账号名称请输入3到20位数字,字母或下划线".rh_localized];
         return;
     }
    
    //验证码校验
    NSString *code =  [(QMUITextField*)self.TFArr[3] text];
     if(![NSString validateVerificationCode:code]){
         [QMUITips showError:@"请输入6位验证码".rh_localized];
         return;
     }
    
    //密码校验
    NSString *password =  [(QMUITextField*)self.TFArr[4] text];
     if(![NSString validatePassword:password]){
         [QMUITips showError:@"密码长度为8 ~ 16，必须包含大写字母、小写字母和数字".rh_localized];
         return;
     }
    
    if (![[(QMUITextField*)self.TFArr[4] text] isEqualToString:[(QMUITextField*)self.TFArr[5] text]]) {
        [QMUITips showError:@"两次输入的密码不一致".rh_localized];
        return;
    };
    
    NSMutableDictionary *para = @{@"email":email,
                           @"userName":userName,
                           @"nickName":userName,
                           @"reCode":code,
                           @"password":[LCMD5Tool md5HexDigest:password],
                           @"brandId": [NetworkConfig sharedConfig].brandID,
                           @"status":@"0",
                           @"platform":@"business"
                         }.mutableCopy;
    if(isBrand){
        //创建国代用户传选择的国家地区,其他角色默认当前登录的国家
        [para setObject:self.regionModel.countryName forKey:@"serverArea"];
    }
    
    [QMUITips showLoadingInView:self.view];
    [BaseModel startWithCompletionAPIKey:H_addUser argument:para requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        if(resultModel.code == 200){
            [QMUITips showSucceed:@"成功".rh_localized inView:self.view hideAfterDelay:1];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                if (self.addSeccusss) {
                    self.addSeccusss();
                }
                [[NSNotificationCenter defaultCenter] postNotificationName:SwitchRegionSuccessNotification object:nil];
                [self.navigationController popViewControllerAnimated:YES];
            });
        }
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        [QMUITips showError:resultModel.message];
    }];
}

//获取国家所有编码
-(void)getCountryByServer
{
    if([NetworkConfig sharedConfig].areaCode.length ==0 ){
        [QMUITips showInfo:@"请重新登录".rh_localized];
        return;
    }
    //根据全球国家编码
    [QMUITips showLoadingInView:self.view];
    NSString *url = [[EnvironmentManage sharedEnvirManage] getBaseAPIUrl];
    [RHGolbalRegionModel startWithBaseUrl:url APIKey:G_getCountryByServer argument:@{@"areaCode":[NetworkConfig sharedConfig].areaCode} requestMethod:RequestMethodPOST requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        if(resultModel.code == 200){
            self.countryListArr = resultModel.data;
            //品牌商创建子用户(国代)的时候,要获取已经存在国代的国家,置灰,不让选择
            if([PrivateMange share].currentUser.hierarchyCode == UserRoleTypeBrandMerchants){
                [self getBrandCountry];
            }else{
                [self showCountryList];
            }
            
        }
        
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        
    }];
    
}

//获取已经有国代的国家
-(void)getBrandCountry
{
    [QMUITips showLoadingInView:self.view];
    [RHGolbalRegionModel startWithCompletionAPIKey:H_getBrandCountry argument:@{} requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        if(resultModel.code == 200){
            if([request.responseJSONObject[@"data"] isKindOfClass:[NSArray class]]){
                NSArray *arr = request.responseJSONObject[@"data"];
                self.filterAreaArr = arr;
            }
            [self showCountryList];
        }
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        
    }];
    
}

-(void)showCountryList
{
    if(self.countryListArr.count == 0){
        [QMUITips showError:@"没有国家列表数据".rh_localized];
        return;
    }
    NSMutableArray *countryArr = [NSMutableArray array];
    for (int i = 0; i<self.countryListArr.count; i++) {
        RHGolbalRegionModel *model = self.countryListArr[i];
        [countryArr addObject:model.countryName];
    }
    RHChioceRegionTypeVC *vc = [[RHChioceRegionTypeVC alloc] initWithData:countryArr];
    vc.fitlerArr = self.filterAreaArr;
    [[RHWindowTipManage shareWindowTipManage] showWithController:vc];
    kWeakSelf;
    vc.selectBlock = ^(NSInteger index) {
        QMUITextField *tf = (QMUITextField*)weakSelf.TFArr[0];
        RHGolbalRegionModel *model = self.countryListArr[index];
        tf.text = model.countryName;
        //国家区域编码
        weakSelf.regionModel = model;
    };
}



#pragma mark ------- 自动填充粘贴板的内容
-(void)appBecomActive
{
    NSString *codeStr = [UIPasteboard generalPasteboard].string;
    NSString *reg = @"[0-9]{6}";
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",reg];
    BOOL isSixNumber = [predicate evaluateWithObject:codeStr];
    if(isSixNumber){
        [(QMUITextField*)self.TFArr[2] setText:codeStr];
    }
    NSLog(@"---->粘贴板的内容:%@",codeStr);
}


-(void)dealloc
{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}



@end
